package com.qiche.controller.mini;

import com.alibaba.fastjson.JSONObject;
import com.qiche.aspect.Result;
import com.qiche.enums.ResultEnum;
import com.qiche.model.User;
import com.qiche.requestpram.DateParamURL;
import com.qiche.service.UserService;
import com.qiche.util.JWTUtil;
import com.qiche.util.UserUtils;
import com.qiche.vo.MiniHomeStatementDatVo;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 微信小程序端 用户管理控制器
 * Created by Linzw on 2018/01/24.
 */
@RestController
@RequestMapping("/wxmini/user")
public class WxminiUserController {
    @Resource
    private UserService userService;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.createByResultEnum(ResultEnum.USERNAME_PASSWORD_IS_NULL);
        }

        Result<User> result=userService.login(user.getUsername(),user.getPassword(),false);
        if(result.isSuccess()){
            User currentUser = UserUtils.getCurrentUser();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("merchantId",currentUser.getMerchantId());
            String token=JWTUtil.sign(currentUser.getUsername(),currentUser.getPassword());
            jsonObject.put("token",token);
            return Result.createByResultEnum(ResultEnum.SUCCESS, jsonObject);
        }
        return  result;
    }

    /**
     * 主页
     * @param dateParamURL
     * @return
     */

    @PostMapping("/home")
    public Result miniHomeStatement(@RequestBody DateParamURL dateParamURL) {
        Date startTime = dateParamURL.getStartTime();
        Date endTime = dateParamURL.getEndTime();
        if (startTime == null || endTime == null) {
            return  Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        User currentUser = UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }

        MiniHomeStatementDatVo miniHomeStatement = userService.getMiniHomeStatement(currentUser, startTime, endTime);
        return Result.createByResultEnum(ResultEnum.SUCCESS, miniHomeStatement);
    }



}
